<template>
    <div>
        <a-row>
            <!-- v-userAuth="'F2'" -->
            <a-row class='mytitle'>
                <div style="cursor: pointer;width: 360px" @click="handleNavigate">
                    <a-icon type="left" />
                    <span>{{ $t('返回') }}</span>
                    <span style="margin-left: 8px;">|</span>
                    <span style="margin-left: 8px">{{ $t('文件系统') }}</span>
                    <span style="margin-left: 8px;">/</span>
                    <span style="margin-left: 8px">{{ $t('Edit') + 'SMB/CIFS' + $t('共享') }}</span>
                </div>
            </a-row>

            <a-row style="margin:1em">
                <a-card hoverable>
                    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol"
                        :wrapper-col="wrapperCol">
                        <a-spin :spinning="loading">
                            <a-form-model-item :label="$t('共享名称')" prop="name">
                                <a-input style="width:470px;" disabled v-model="form.name" :placeholder="$t('Enter') + $t('共享名称')" />
                            </a-form-model-item>
                            <a-form-model-item :label="$t('目录选择')" prop="path">
                                <a-input style="width:380px;" disabled v-model="form.path" :placeholder="$t('请输入或选择目录路径')" />
                                <a-button disabled style="margin-left: 16px;" type='primary' @click="handleChoose">
                                    <Iconfont class="icon button-icon-style" type="icon-view16f"></Iconfont>
                                    {{ $t('浏览') }}
                                </a-button>
                                <a-checkbox disabled v-model="form.isCreate">
                                    {{ $t('如果目录不存在，则创建新目录') }}
                                </a-checkbox>
                            </a-form-model-item>

                            <a-form-model-item :label="$t('访问模式')" prop="access_type" @change="accessTypeChange">
                                <a-radio-group disabled v-model="form.access_type">
                                    <a-radio v-for="item of accessGroup" :value="item.value" :key="item.value">{{ item.label
                                    }}</a-radio>
                                </a-radio-group>
                            </a-form-model-item>

                            <a-form-model-item v-if="form.access_type == 1" :label="$t('基于访问的共享枚举(ABE)')" prop="abe">
                                <a-switch :checked="abe" @change="switchChange" />
                            </a-form-model-item>

                            <a-form-model-item v-if="form.access_type == 1" :label="$t('共享方式')" prop="share_mode">
                                <a-radio-group disabled v-model="form.share_mode">
                                    <a-radio v-for="item of shareGroup" :value="item.value" :key="item.value">
                                        {{ item.label }}
                                        <a-tooltip placement='top'>
                                            <template slot='title'>
                                                <span v-if="item.value == 1">{{
                                                    $t('共享上方选择的目录路径的空间，会为有权限的用户创建属于自己的子目录，可以通过输入用户及密码，在新创建的子目录中进行读写 / 只读操作')
                                                }}</span>
                                                <span v-else-if="item.value == 2">{{
                                                    $t('共享上方选择的目录的所有文件及子目录，有权限的用户（组）可通过输入用户及密码，或匿名访问的方式，进行该路径文件及子目录的读写')
                                                }}</span>
                                            </template>
                                            <Iconfont class="icon table-operation-icon" type="a-16_f_ic_about"></Iconfont>
                                        </a-tooltip>
                                    </a-radio>
                                </a-radio-group>
                            </a-form-model-item>

                            <!-- <a-form-model-item :label="$t('操作权限')" prop="name">
                                <a-radio-group v-model="form.access_type">
                                    <a-radio v-for="item of permissionGroup" :value="item.value" :key="item.value">{{ item.label
                                    }}</a-radio>
                                </a-radio-group>                        
                            </a-form-model-item> -->

                            <a-form-model-item v-if="form.access_type == 1" :label="$t('共享用户(组)')"
                                :wrapper-col="{ span: 20 }" prop="share_info">
                                <a-button type='primary' @click="handleCreate">
                                    <Iconfont class="icon button-icon-style" type="icon-new16f"></Iconfont>
                                    {{ $t('添加用户(组)权限') }}
                                </a-button>
                                <a-table v-if="isShow" style="margin-top: 12px;" rowKey="index" :columns='columns'
                                    :dataSource='form.share_info' :locale="defaultSetting" :pagination='pagination'
                                    size='small'>
                                    <template slot="share_type" slot-scope="share_type">
                                        <span>{{ shareMap.get(share_type) }}</span>
                                    </template>
                                    <template slot="user_type" slot-scope="user_type, record">
                                        <span v-if="user_type == 1 && record.share_type == 1">本地用户</span>
                                        <span v-if="user_type == 1 && record.share_type == 2">AD用户</span>
                                        <span v-if="user_type == 2 && record.share_type == 2">AD用户组</span>
                                        <!-- <span>{{ userMap.get(user_type) }}</span> -->
                                    </template>
                                    <template slot="permission" slot-scope="permission, record">
                                        <a-radio-group v-if="isShow" v-model="permission" @change="radioChange"
                                            :name="record.id + ''">
                                            <a-radio :value="1">{{ $t('只读') }}</a-radio>
                                            <a-radio :value="2">{{ $t('读写') }}</a-radio>
                                        </a-radio-group>
                                    </template>
                                    <template slot="operate" slot-scope='text, record'>
                                        <div style="display: flex;">
                                            <a-tooltip placement='top'>
                                                <template slot='title'>
                                                    <span>{{ $t('Delete') }}</span>
                                                </template>
                                                <Iconfont class="icon table-operation-icon" type="icon-delete16f"
                                                    @click="handleDelete(record, record.index)"></Iconfont>
                                            </a-tooltip>
                                        </div>
                                    </template>
                                </a-table>
                            </a-form-model-item>

                            <a-form-model-item v-if="form.access_type == 2" :label="$t('操作权限')" prop="name">
                                <a-radio-group v-model="form.authorization">
                                    <a-radio v-for="item of permissionGroup" :value="item.value" :key="item.value">{{
                                        item.label
                                    }}</a-radio>
                                </a-radio-group>
                            </a-form-model-item>

                            <a-form-model-item :wrapper-col="{ span: 4, offset: 4 }">
                                <a-button type="primary" @click="onSubmit">
                                    {{ $t('Save') }}
                                </a-button>
                                <a-button style="margin-left: 10px;" @click="handleClose">
                                    {{ $t('Cancel') }}
                                </a-button>
                            </a-form-model-item>
                        </a-spin>
                    </a-form-model>
                </a-card>
            </a-row>

        </a-row>

        <chooseDirectory ref="directoryRef" />
        <appendDialog ref="createRef" @submit-form="submitForm" :defaultList="defaultList" />

    </div>
</template>
<script>
import NoAuthPage from '@/components/common/NoAuthPage'
import EmptyData from '@/components/common/EmptyData'
import chooseDirectory from '../directory/chooseDirectory.vue'
import appendDialog from './appendDialog.vue'
import { shareMap, userMap } from "./data";

export default {
    components: { EmptyData, NoAuthPage, chooseDirectory, appendDialog },
    data() {
        return {
            loading: false,
            copyList: [],
            defaultSetting: { emptyText: <EmptyData /> },
            pagination: {
                defaultPageSize: 10,
                showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
                showSizeChanger: true,
                pageSizeOptions: ['5', '15', '20', '25'],
                onShowSizeChange: (current, pageSize) => this.pageSize = pageSize,
                buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
            },
            columns: [
                { title: this.$t('名称'), dataIndex: 'user', key: 'user' },
                { title: this.$t('共享类型'), dataIndex: 'share_type', scopedSlots: { customRender: 'share_type' } },
                { title: this.$t('用户类型'), dataIndex: 'user_type', scopedSlots: { customRender: 'user_type' } },
                { title: this.$t('权限'), dataIndex: 'permission', scopedSlots: { customRender: 'permission' } },
                { title: this.$t('Operate'), key: "operate", scopedSlots: { customRender: 'operate' }, width: 200 }
            ],
            labelCol: { span: 4 },
            wrapperCol: { span: 10 },
            form: {
                name: '',
                path: '',
                isCreate: false,
                access_type: 1,
                share_mode: 1,
                authorization: 1,
                share_info: [],
                operate: 'update',
                abe: 0,
            },
            rules: {
                name: [
                    { required: true, message: this.$t('Enter') + this.$t('共享名称'), trigger: 'blur' },
                    { pattern: /^[A-Za-z0-9_]{3,16}$/, message: this.$t('名称仅支持大小写英文字母 + 数字 + 英文下划线，3-16个字符'), trigger: 'blur' }
                ],
                path: [
                    { required: true, validator: (rules, value, callback) => { this.pathValidator(rules, value, callback) }, trigger: 'blur' },
                ],
                access_type: [
                    { required: true, message: this.$t('Choose') + this.$t('访问模式'), trigger: 'change' },
                ],
                share_mode: [
                    { required: true, message: this.$t('Choose') + this.$t('共享方式'), trigger: 'change' },
                ],
                abe: [
                    { required: true, message: this.$t('Choose') + 'ABE', trigger: 'change' },
                ],
            },
            shareMap,
            userMap,
            isShow: true,
            accessGroup: [
                { value: 1, label: '用户访问' },
                { value: 2, label: '匿名访问' },
            ],
            shareGroup: [
                { value: 1, label: '共享目录空间' },
                { value: 2, label: '共享当前目录' },
            ],
            permissionGroup: [
                { value: 1, label: '只读' },
                { value: 2, label: '读写' },
            ],
            defaultList: [],
        }
    },
    computed: {
        abe() {
            return !!this.form.abe
        }
    },
    async mounted() {
        if (this.$route.query.dir_name) {
            this.form.path = this.$route.query.dir_name
            this.$router.push({ query: {} })
        }
        const item = JSON.parse(decodeURIComponent(this.$route.query.item))
        this.form = { ...this.form ,...item }
        await this.getList(this.form.id)
    },
    methods: {
        switchChange(value) {
            this.form.abe = Number(value)
        },
        accessTypeChange() {
            if (this.form.access_type == 2) this.form.abe = 0
        },
        async getList(share_id) {
            this.loading = true
            const { data } = await this.$api.directory.getShareInfoApi({ share_id })
            this.form.share_info = data.samba_user
            this.loading = false
            const list = []
            this.form.share_info.map(item => {
                if (item.user_id) {
                    if (item.share_type == 1 && item.user_type == 1) {
                        item.index = 'samba' + item.user_id
                        list.push('samba' + item.user_id)
                    }
                    else if (item.share_type == 2 && item.user_type == 1) {
                        item.index = 'ad' + item.user_id
                        list.push('ad' + item.user_id)
                    }
                    else if (item.share_type == 2 && item.user_type == 2) {
                        item.index = 'adGroup' + item.user_id
                        list.push('adGroup' + item.user_id)
                    }
                }
            })
            this.$refs.createRef.targetKeys = list
        },
        handleChoose() {
            this.$refs.directoryRef.isShow = true
        },
        handleCreate() {
            this.$refs.createRef.isShow = true
            this.defaultList = this.form.share_info
        },
        submitForm(list) {
            this.isShow = false
            let newList = []
            list.map(item => {
                if (this.form.share_info.length === 0) {
                    newList = list
                }
                else {
                    const index = this.form.share_info.findIndex(subItem => subItem.index == item.index)
                    if (index == '-1') newList.push(item)
                }
            })
            this.form.share_info = this.form.share_info.concat(newList)
            this.isShow = true
        },
        handleNavigate() {
            this.$router.push({ path: '/fsview' })
        },
        onSubmit() {
            this.$refs.ruleForm.validate(async valid => {
                if (valid) {
                    this.loading = true
                    const { data } = await this.$api.directory.createShareApi(this.form)
                    this.model(data.id) //返回模板
                    this.notice(data.id, data.params, data.flag) //通知列表显示
                    if (data.flag == '0') this.$router.push({ path: '/fsview' })
                    this.loading = false
                } else {
                    return false;
                }
            });
        },
        async handleDelete(item) {
            const { share_mode } = this.form
            const { name: share_name, id: share_id } = this.form
            const { user, share_type } = item
            const params = { share_name, share_id, user, share_type, share_mode }
            await this.deleteCallback(user, params)
        },
        deleteCallback(name, params) {
            this.loading = true
            let _this = this
            this.$confirm({
                title: this.$t('删除共享'),
                content: this.$t('删除共享用户名为') + `${name}` + this.$t('后，将无法恢复！您确定要删除吗？'),
                cancelText: this.$t('Cancel'),
                okText: this.$t('Sure'),
                okType: 'danger',
                icon: 'close-circle',
                async onOk() {
                    const { data } = await _this.$api.directory.deleteShareUserApi(params)
                    _this.model(data.id) //返回模板
                    _this.notice(data.id, data.params, data.flag) //通知列表显示
                    if (data.flag == '0') _this.getList(_this.form.id)
                    return data.flag
                },
                onCancel() {
                }
            })
            this.loading = false
        },
        radioChange({ target: { name, value } }) {
            // name 列表索引
            this.isShow = false
            this.form.share_info.map(item => {
                if (item.id == name) item.permission = value
                return item
            })
            this.isShow = true
        },
        handleClose() {
            this.$router.push({ path: '/fsview' })
        },
        pathValidator(rule, value, callback) {
            if (value == '') callback(this.$t('Choose') + this.$t('目录路径'))
            // if (value == '/') callback()
            else {
                const reg = /^(\/[\w.-]+)+\/?$/
                if (!reg.test(value)) callback(this.$t('Choose') + this.$t('请输入或选择目录路径'))
                else callback()
            }
        },
    }
}
</script>


<style scoped>
.title {
    color: #666666;
}

.size14 {
    font-size: 14px;
}

.line {
    width: 100%;
    border-bottom: solid 1px #cccccc;
    line-height: 0.9;
}

.shallow {
    color: #666666;
}

.mt-7 {
    margin-top: 7px;
}

.cont {
    color: #333333;
    font-weight: bolder;
}</style>
